package ar.com.larctest.providers;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import ar.com.larctest.dbHelper.SQLLARCTESTHelper;
import ar.com.larctest.entities.Temperature;

public class TemperatureProvider {
    private static final String TAG = "TemperatureProvider";

	private static final String DB_COLUMN_0_NAME = "idTemperature";
	private static final String DB_COLUMN_1_NAME = "description";

	private SQLiteDatabase database;
	private SQLLARCTESTHelper dbHelper;
	private String[] allColumns = {DB_COLUMN_0_NAME, DB_COLUMN_1_NAME};

	public TemperatureProvider(Context context) {
		dbHelper = SQLLARCTESTHelper.getHelper(context);
		database = dbHelper.getWritableDatabase();
	}

	public Temperature getTemperature(Integer idTemperature)
	{
        Cursor cursor = null;
        Temperature temperature = null;

        try
		{
			cursor = database.query(SQLLARCTESTHelper.DB_TEMPERATURE_TABLE_NAME, allColumns, DB_COLUMN_0_NAME + " = " + idTemperature, null, null, null, null);
			cursor.moveToFirst();

            temperature = new Temperature();
            temperature.setIdTemperature(cursor.getInt(0));
            temperature.setDescription(cursor.getString(1));

			return temperature;
		}
		catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return temperature;
		}
        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
	}
	
	public List<Temperature> getTemperature()
    {
        Cursor cursor = null;
		List<Temperature> lstTemperature = new ArrayList<Temperature>();

        try
        {
            cursor = database.query(SQLLARCTESTHelper.DB_TEMPERATURE_TABLE_NAME, allColumns, null, null, null, null, null);
            cursor.moveToFirst();

            while (!cursor.isAfterLast()) {
                Temperature temperature = new Temperature();
                temperature.setIdTemperature(cursor.getInt(0));
                temperature.setDescription(cursor.getString(1));

                lstTemperature.add(temperature);
                cursor.moveToNext();
            }
            cursor.close();
            return lstTemperature;
        }
        catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return lstTemperature;
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
	}
}
